package ar.edu.unq.wannaplay.services;

import java.util.LinkedList;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import ar.edu.unq.wannaplay.exceptions.BlankStringException;
import ar.edu.unq.wannaplay.exceptions.IncorrectPasswordException;
import ar.edu.unq.wannaplay.exceptions.NullArgumentException;
import ar.edu.unq.wannaplay.exceptions.UserAlreadyExistsException;
import ar.edu.unq.wannaplay.exceptions.UserDoesNotExistException;
import ar.edu.unq.wannaplay.persistence.daos.UserDAO;
import ar.edu.unq.wannaplay.users.Role;
import ar.edu.unq.wannaplay.users.User;
import ar.edu.unq.wannaplay.utils.Service;

public class UserService implements Service {
    private static final long serialVersionUID = 1L;

    private UserDAO dao;

    @Transactional
    public void login(final String username, final String password) throws UserDoesNotExistException,
            IncorrectPasswordException {
        String trimUsername = username.trim();
        User user = this.getDao().findByUsername(trimUsername);
        if (user == null) {
            throw new UserDoesNotExistException("The user does not exist");
        } else if (!user.getPassword().equals(password)) {
            throw new IncorrectPasswordException("the password is incorrect");
        }
    }

    @Transactional
    public void register(final String username, final String password, final Role role)
            throws UserAlreadyExistsException, BlankStringException, NullArgumentException {

        if (role == null) {
            throw new NullArgumentException("You didn't select a combo element");
        }
        String trimUsername = username.trim();
        if ("".equals(trimUsername)) {
            throw new BlankStringException("The string is empty");
        } else {
            User user = this.getDao().findByUsername(trimUsername);
            if (user == null) {
                this.getDao().save(new User(username, password, role));
            } else {
                throw new UserAlreadyExistsException("The user already exists");
            }
        }
    }

    @Transactional
    public List<Role> findAllRoles() {
        List<Role> list = new LinkedList<Role>();
        for (Role current : Role.values()) {
            list.add(current);
        }
        return list;
    }

    @Transactional
    public Role getUserRole(final String username) {
        User user = this.getDao().findByUsername(username);
        return user.getRole();
    }

    public UserDAO getDao() {
        return dao;
    }

    public void setDao(final UserDAO dao) {
        this.dao = dao;
    }

    @Override
    public Object toDto(final Object object) {
        throw new UnsupportedOperationException();
    }

}
